from brian import *
from brian.library.random_processes import *
from brian.library.synapses import  *
import MoNeuron as Moto
import RNeuron as Renshaw
import InNeuron as IN
from time import clock
from MyConstants import gSynE, gSynI
from matplotlib.backends.backend_pdf import PdfPages
from time import clock
from brian.tools.datamanager import *
from brian.tools.taskfarm import *

class MN_threshold:
    N = 1000
    DUR=50*ms
    def __init__(self):
        
        
        
        self.MNFactory=Moto.MnNeuronFactory()
        self.MN=self.MNFactory.init(self.N,'alpha',1,False)
        
        self.spiketimes = []
        for i in xrange(0,self.N):
             self.spiketimes.append((i,4*ms))
        
        self.AfferentInput = SpikeGeneratorGroup(self.N,self.spiketimes,period=1/(10*Hz))
        
        self.C_Aff_MN=Connection(self.AfferentInput,self.MN,'ge',weight=1/self.N*0.05*msiemens*cm**-2,sparseness=1)
        
        self.spikeMN = SpikeMonitor(self.MN)
        
        
        @network_operation(clock=EventClock(dt=200*ms))
        def progress(clk):
            print clk._t
            return
                
        self.net=Network(self.MN,self.AfferentInput,self.C_Aff_MN,self.spikeMN,progress)
        
    def __call__(self,k,report):
        self.C_Aff_MN.__init__(self.AfferentInput,self.MN,'ge',weight=k/self.N*0.05*msiemens*cm**-2,sparseness=1)
        start = clock()
        self.net.run(self.DUR,report=report)
        stop = clock()
        print 'Duration ' + str(stop-start)
        
        excited = zeros(self.N)
        for i in xrange(0,self.N):
            excited[i] = 1 if self.spikeMN.spiketimes[i].__len__() >= 1 else 0
        
        print 'weight = ' + str(k) + ' count = ' + str(sum(excited))    
        return (k,sum(excited))



if __name__ == '__main__':
    N_run = 100
    dataman = DataManager('MN_threshold')
    weights = linspace(0,20,N_run)
    run_tasks(dataman, MN_threshold, weights)
        
    X, Y = zip(*dataman.values())
    plot(X, Y, '.')
    xlabel('strength')
    ylabel('count firing')
    show()